package com.tedu.bill.demo4;

import java.io.*;

/**
 * Author：毕龙
 * Date: 2024/5/28 11:18
 */
public class AppendSaveObject {
    private static final String FILE_PATH = "people.txt";

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        File file = new File(FILE_PATH);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("------------------ " + FILE_PATH + " 文件删除成功 ------------------\n");
            }
        }

        // Important: 在创建 ObjectOutputStream 类的实例前先初始化该类的文件信息
        AppendObjectOutputStream.initFile(file);

        // new ObjectOutputStream(new FileOutputStream(FILE_PATH, true)) => new AppendObjectOutputStream(file)
        ObjectOutputStream oos = new AppendObjectOutputStream(file);
        oos.writeObject(new User("Tom", "123"));
        oos.writeObject(new User("Smith", "123"));
        oos.close();

        // 初次反序列化读取已保存的对象信息，正常读取
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_PATH));
        System.out.println("第一次读取到的的对象信息：" + ois.readObject());
        System.out.println("第一次读取到的的对象信息：" + ois.readObject());
        ois.close();


    }

}
